package com.ityj.yygh.user.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ityj.yygh.result.Result;
import com.ityj.yygh.user.utils.ConstantUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@Api(value = "微信登录相关接口")
@Controller
@RequestMapping(path = "/api/ucenter/wx")
@Slf4j
public class WxApiController {

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation("获取微信登录参数")
    @GetMapping(path = "/getLoginParam")
    @ResponseBody
    public Result<Map<String, Object>> genQrConnect() {
        Map<String, Object> result = new HashMap<>();
        result.put("appid", ConstantUtils.WX_OPEN_APP_ID);
        result.put("redirectUri", URLEncoder.encode(ConstantUtils.WX_OPEN_REDIRECT_URL));
        result.put("scope", "snsapi_login");
        result.put("response_type", "code");
        result.put("state", Instant.now().getNano());
        return Result.ok(result);
    }

    @ApiOperation("微信登录回调:获取并解析access_token进行登录")
    @GetMapping(path = "/callback")
    public String callBack(String code, String state) {
        // 获取授权的临时票据
        log.info("code = {}, state = {}", code, state);
        // 1. 通过code获取access_token
        // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String accessTokenUrl = String.format(ConstantUtils.GET_ACCESS_TOKEN_URL,
                ConstantUtils.WX_OPEN_APP_ID,
                ConstantUtils.WX_OPEN_APP_SECRET,
                code,
                "authorization_code");
        ResponseEntity<String> accessTokenEntity = restTemplate.getForEntity(accessTokenUrl, String.class);
        JSONObject jsonObject = JSON.parseObject(accessTokenEntity.getBody());
        String accessToken = (String) jsonObject.get("access_token");
        String openid = (String) jsonObject.get("openid");
        log.info("access_token = {}, openid = {}", accessToken, openid);

        // 2. 获取用户个人信息（UnionID机制）
        // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        String userInfoUrl = String.format(ConstantUtils.GET_USER_INFO_URL,
                accessToken,
                ConstantUtils.WX_OPEN_APP_ID);
        ResponseEntity<String> userInfoEntity = restTemplate.getForEntity(userInfoUrl, String.class);
        JSONObject userInfoObject = JSON.parseObject(userInfoEntity.getBody());
        String nickname = (String) userInfoObject.get("nickname");
        Object sex = userInfoObject.get("sex");
        String province = (String) userInfoObject.get("province");
        String city = (String) userInfoObject.get("city");
        String country = (String) userInfoObject.get("country");
        String headimgurl = (String) userInfoObject.get("headimgurl");
        Object privilege = userInfoObject.get("privilege");
        log.info("nickname = {}, sex = {}, province = {}, privilege = {}", nickname, sex, province, privilege);
            
        return "redirect:" + ConstantUtils.YYGH_BASE_URL +
                "/weixin/callback?token=" + accessToken + "&openid=" + openid + "&name=";
    }
}
